import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import bcrypt from "bcrypt";
import { Organization } from "@db";
import { config } from "@config";
import { sendCode } from "@helpers";
import axios from "axios";

//Подробнее о возможностях валидации лучше смотреть тут - https://github.com/sinclairzx81/typebox
const signUpBody = Type.Object({
    INN: Type.String(),
    email: Type.String({ format: "email" }),
    password: Type.String({ minLength: 6, maxLength: 512 }),
});

export const signUp = async (fastify: FastifyInstance) => {
    fastify.post<{ Body: Static<typeof signUpBody> }>(
        "/organization/signUp",
        {
            schema: {
                tags: ["organization"],
                body: signUpBody,
            },
        },
        async (req, res) => {
            const { INN, email, password } = req.body;

            const organizationExists = await Organization.findOne({
                where: {
                    email,
                },
            });
            if (organizationExists)
                return res.status(409).send({
                    code: "EMAIL_EXISTS",
                    message:
                        "На этот адрес эл. почты уже зарегестрирован аккаунт",
                });

            const [organizationInfo] = await axios
                .post(
                    "https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party",
                    { query: INN },
                    {
                        headers: {
                            Authorization: "Token " + config.dadata.token,
                            "X-Secret": config.dadata.secretKey,
                        },
                    }
                )
                .then((res) => res.data.suggestions);

            console.log(organizationInfo);
            const hash = bcrypt.hashSync(password, config.saltRounds);
            const [lastName, firstName] =
                organizationInfo.data.management.name.split(" ");

            const organization = await Organization.create({
                name: organizationInfo.value,
                email,
                password: hash,
                contactPersons: [
                    {
                        firstName,
                        lastName,
                        jobName: organizationInfo.data.management.post,
                        contacts: {
                            vk: null,
                            telegram: null,
                            github: null,
                        },
                    },
                ],
                addresses: [organizationInfo.data.address.value],
            });
            await sendCode(organization.email, "organization");

            //пишем в сессию (которая секьюрная да-да)
            req.session.organization = { id: organization.id };
            return res.status(201).send({
                ...organization.dataValues,
                photo: organization.photo
                    ? "https://" +
                      config.host +
                      "/files/organizationAvatars/" +
                      organization.photo
                    : null,
                password: undefined,
                updatedAt: undefined,
            });
        }
    );
};
